<template>
	<s-layout title="标题" navbar="normal1">
		<view class="navbar">
			<su-status-bar v-if="!sheep.$platform.inApp" />
			<view class="navbar-placeholder" />
			<view class="navbar-center ss-flex ss-col-bottom" :style="{ height : statusBarHeight + 44 + 'px'}">
				<view class="ss-flex w-100" style="height: 44px;">
					<view class="ss-flex-1 ss-flex ss-row-between ss-p-x-20 w-100">
						<view class="leftBox ss-flex">
							<view class="leftBox-title ss-flex">
								<view class="leftBox-iconBox"  @click="onClickLeft">
									
									<image class="leftBox-icon" src="/static/tuangou/left.png" mode="aspectFill" />
								</view>
								<view :style="{opacity:state.navOpacity}">
									团购
								</view>
							</view>
							<view class="leftBox-location ss-flex ss-m-l-16" :style="{opacity:state.navOpacity}"
								@click="onchangeArea">
								<uni-icons type="location-filled" size="18" color="#585858" />
								<view class="location-name">{{ state.params.area }}</view>
								<image class="location-icon" src="/static/tuangou/right.png" mode="aspectFill" />
							</view>
						</view>
						<view class="rightBox ss-flex" @click="openOrder" :style="{opacity:state.navOpacity}">
							<image class="rightBox-icon" src="/static/tuangou/order.png" mode="aspectFill" />
							订单
						</view>
					</view>
					<!-- #ifdef MP -->
					<view v-if="!sheep.$platform.inPc" :style="[capsuleStyle]"></view>
					<!-- #endif -->
					<view v-if="sheep.$platform.inApp" :style="[capsuleStyle]"></view>
				</view>
			</view>
		</view>
		<view class="search" :style="{top:statusBarHeight + 'px',	
			paddingLeft: 15 + (20*( 1 - state.navOpacity)) + 'px',
			paddingRight: 15 + (capsuleWidth*(1 - state.navOpacity)) + 'px'}">
			<view class="search-box ss-flex ss-row-between">
				<view class="city" @click="onchangeArea">
					<view class="city_name">{{ state.params.area }}</view>
					<image class="down" src="/icon/down.png" mode="aspectFill" />
				</view>
				<view class="line"></view>
				<input type="text" class="keyword" @confirm="inputSearch" v-model="state.params.title"
					placeholder="搜索本地生活店铺" />
				<view class="search_btn" @click="onSearch">搜索</view>
			</view>
		</view>
		<scroll-view scroll-x id="menuList" class="menuList" :style="{top:statusBarHeight + 'px',
			background:`rgba(255,255,255,${1 - state.classOpacity})`}">
			<view :class="['menuList-item ss-flex-col ss-col-center',
				{[state.classOpacity>= 1 ?'active':'active1']:state.params.tag_id == item.id}]"
				v-for="item in state.classList" :key="item.icon"  @click="setMenuList(item)">
				<view class="itemBox ss-flex-col ss-col-center ss-row-between">
					<image class="menuList-img" :style="{opacity:state.classOpacity}"
						:src="sheep.$url.cdn(item.icon,'ygb')" />
					<view class="menuList-title">
						<text class="menuList-title-text">{{item.tag_name}}</text>
						<view class="menuList-title-line" />
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="content">
			<view class="tejiatuan">
				<view class="tejiatuan-title ss-flex">
					<view class="title">
						特价团
					</view>
					<view class="heat">
						低价热抢中
					</view>
				</view>
				<view class="tejiatuan-goodsBox ss-flex ss-flex-wrap">
					<view class="goodsBox-item ss-flex" v-for="item in state.tjList" :key="item.id + 'tg'">
						<image class="item-img"
							:src="sheep.$url.cdn(item.image,'ygb')" />
						<view class="item-right ss-flex-col ss-row-between">
							<view class="item-right-title ss-line-2">
								{{item.store_name + item.title}}
							</view>
							<view class="item-right-price ss-flex ss-col-bottom">
								￥{{item.price}}
								<view class="price-line" v-if="item?.linePrice">
									￥{{item?.linePrice}}
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<cDropMenu :data="state.dropMenu" @change="dropMenuChange">
				<view id="listBox">
					<cGroupCard :data="item" v-for="item in state.list" :key="item.id" />
				</view>
				<uni-load-more v-if="state.list.length > 0" :status="state.more" :content-text="{
					contentdown: '上拉加载更多',
				  }" @tap="loadmore" />
				<s-empty v-if="state.list.length == 0"
					icon="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/mengchong/soldout-empty.png" text="暂无数据">
				</s-empty>
			</cDropMenu>
		</view>
	</s-layout>
</template>

<script setup>
	import sheep from '@/sheep';
	import cDropMenu from "@/components/c-drop-menu.vue"
	import cGroupCard from "./components/c-group-card.vue"
	import mockData from "./data.json"
	import tgAPI from "@/sheep/api/tuangou"
	import {
		ref,
		reactive,
		computed,
		nextTick,
		getCurrentInstance,
	} from 'vue'
	import {
		onLoad,
		onShow,
		onHide,
		onPageScroll,
		onReachBottom,
		onPullDownRefresh
	} from '@dcloudio/uni-app';
	const statusBarHeight = sheep.$platform.device.statusBarHeight;
	const location = sheep.$store('location')
	const state = reactive({
		navRetract: false,
		navOpacity: 1,
		classOpacity: 1,
		data: {},
		scrollTop:0,
		pages:0,
		list: [],
		tjList:[],
		more: 'more',
		params: {
			area: '杭州市',
			tag_id:'',
			title: '',
			lng: location.myPosition.longitude,
			lat: location.myPosition.latitude,
		},
		dropMenu: [{
				label: '附近',
				key: 'near',
				value: '',
				children: [{
						label: '全部',
						value: '',
					},
					{
						label: '500m',
						value: '500',
					},
					{
						label: '1km',
						value: '1000',
					},
					{
						label: '2km',
						value: '2000',
					},
					{
						label: '5km',
						value: '5000',
					},
					{
						label: '≥5km',
						value: '5000+',
					},
				]
			},
			{
				label: '智能排序',
				key: 'sort',
				value: '',
				children: [{
					label: '最近距离',
					value: 'distance',
				}, ]
			},
			{
				label: '必吃套餐',
				key: 'recommend',
				value: '1',
				children: []
			},
			{
				label: '高分店',
				key: 'highScore',
				value: '1',
				children: []
			}
		],
		classList:[]
	})
	const { proxy }= getCurrentInstance()
	const navHeight = computed(() => {
		if (state.navRetract) {
			return statusBarHeight + 44 + uni.rpx2px(60)
		} else {
			return statusBarHeight + 44 + uni.rpx2px(80) + uni.rpx2px(128)
		}
	})
	onLoad(async (opt) => {
		await getLocation()
		init()
	})
	onReachBottom(()=>{
		loadmore()
	})
	onPageScroll((e) => {
		state.scrollTop = e.scrollTop
		let navTran = (30 - e.scrollTop) / 30
		let classTran = (75 - e.scrollTop) / 75
		if (navTran >= 1) {
			state.navOpacity = 1
		} else if (navTran <= 0) {
			state.navOpacity = 0
		} else {
			state.navOpacity = navTran.toFixed(2)
		}
		if (classTran >= 1) {
			state.classOpacity = 1
		} else if (classTran <= 0) {
			state.classOpacity = 0
		} else {
			state.classOpacity = classTran.toFixed(2)
		}
		if (e.scrollTop >= 60) {
			state.navRetract = true;
		} else {
			state.navRetract = false;
		}
	})
	onPullDownRefresh(() => {
		resetList()
		setTimeout(() => {
			getList()
			setMenuList()
			uni.stopPullDownRefresh()
		},300)
	})
	async function init(){
		resetList()
		getSpecialOffer()
		await getTagList()
		await getList()
	}
	function resetList(){
		state.more = 'more'
		state.pages=0
		state.list=[]
		state.tjList=[]
	}
	const hasHistory = sheep.$router.hasHistory();
	function onClickLeft() {
		if (hasHistory) {
			sheep.$router.back();
		} else {
			sheep.$router.go('/pages/index/home');
		}
	}
	async function getLocation(){
		try{
			let data = await location.getLocation()
			state.params.lat = data.latitude
			state.params.lng = data.longitude
		}catch(e){
			state.params.lat = location.myPosition.latitude
			state.params.lng = location.myPosition.longitude
		}
	}

	async function setMenuList(item){
		if(item){
			state.params.tag_id = item.id
		}
		resetList()
		await getList()
		let offsetTop = uni.rpx2px(140) + uni.rpx2px(15) + statusBarHeight
		uni.createSelectorQuery().in(proxy).select("#listBox")
		  .boundingClientRect((data) => {
			if(data.top !== offsetTop ){
				uni.pageScrollTo({
					duration:240,
					scrollTop:state.scrollTop + ( data.top - offsetTop)
				})
			}
		  })
		  .exec();
	}
	function dropMenuChange(e) {
		console.log("dropMenuChange", e)
	}

	function loadmore() {
		getList()
	}
	async function getList(){
		if(state.more == 'noMore')return uni.showToast({
			title:'没有更多了',
			icon:'none'
		})
		state.more = 'loading'
		let { error,data} = await tgAPI.tgGoodsList({ 
			...state.params,
			page:state.pages + 1,
			list_rows: 8
		})
		if(error == 0){
			state.more = data.data.length ==data.per_page?  'more' : 'noMore'
			state.pages = data.current_page
			state.list.push(...data.data)
		}
	}
	function inputSearch() {

	}
	/**
	 * 获取标签列表
	 */
	async function getTagList(){
		let {data ,error} = await tgAPI.tgTagList()
		if(error == 0){
			state.classList  = data
			if(data?.length > 0){
				state.params.tag_id = data[0].id
			}
		}
	}
	/**
	 * 获取特价团商品
	 */
	async function getSpecialOffer(){
		let {data ,error} = await tgAPI.getBargingList({
			lng:state.params.lng,
			lat:state.params.lat,
			page:1,
			list_rows: 4
		})
		if(error == 0){
			state.tjList  = data.data
		}
	}
	function onSearch() {
		sheep.$router.go('/pages/merchant/list',{
			search:state.params.title
		})
	}
	function openOrder() {
		sheep.$router.go('/pages/order/list')
	}
	const capsuleWidth = computed(() => {
		// #ifdef MP
		if (!sheep.$platform.inPc) {
			return sheep.$platform.capsule.width
		}
		// #endif
		return 0
	});
	const capsuleStyle = computed(() => {
		return {
			width: sheep.$platform.capsule.width + 'px',
			minWidth: sheep.$platform.capsule.width + 'px',
			height: sheep.$platform.capsule.height + 'px',
			margin: '0 ' + (sheep.$platform.device.windowWidth - sheep.$platform.capsule.right) + 'px 0 0',
		};
	});

	function changeAddress() {
		if (uni.getStorageSync('location')) {
			state.location = JSON.parse(uni.getStorageSync('location'));
			state.params.area = state.location.city_name;
			// state.params.lng = state.location.lon;
			// state.params.lat = state.location.lat;
		}
		init()
	};
	// 切换城市
	function onchangeArea() {
		// #ifdef APP
		if (sheep.$store('permission').locate === 1) {
			// #endif
			uni.navigateTo({
				url: '/pages/etc/chooseArea',
				events: {
					// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
					acceptDataFromOpenedPage: function(data) {
						changeAddress();
					},
				},
				success: function(res) {
					// 通过eventChannel向被打开页面传送数据
					res.eventChannel.emit('acceptDataFromOpenerPage', {});
				},
			});
			// #ifdef APP
		}
		// #endif
	};
</script>

<style lang="scss" scoped>
	view {
		box-sizing: border-box;
	}

	.navbar {
		background-color: #fff;


		.navbar-placeholder {
			height: 44px;
		}

		.navbar-center {
			width: 100vw;
			max-width: 100vw;
			position: fixed;
			top: 0;
			z-index: 100;
			background-color: #fff;

			.leftBox {
				.leftBox-iconBox{
					padding-left: 14rpx;
					padding-right: 20rpx;
					.leftBox-icon {
						width: 14rpx;
						height: 37rpx;
						vertical-align: middle;
					}
				}
				
				.leftBox-title {
					font-size: 36rpx;
					font-weight: 500;
					line-height: normal;
					text-align: center;
					color: #000000;
				}

				.leftBox-location {
					.location-name {
						font-size: 26rpx;
						font-weight: 500;
						line-height: normal;
						text-align: center;
						color: #2C2C2C;
					}

					.location-icon {
						margin-left: 6rpx;
						width: 24rpx;
						height: 24rpx;
						vertical-align: middle;
					}
				}
			}

			.rightBox {
				padding-right: 14rpx;

				.rightBox-icon {
					margin-right: 4rpx;
					width: 24rpx;
					height: 24rpx;
					vertical-align: middle;
				}

				font-size: 26rpx;
				font-weight: 500;
				line-height: normal;
				text-align: center;
				color: #2C2C2C;
			}
		}
	}


	.search {
		position: sticky;
		width: 100%;
		height: 88rpx;
		z-index: 105;
		padding: 10rpx 30rpx;
		transition: 0.1s;
		pointer-events:none;
		.search-box {
			transition: 0.1s;
			height: 68rpx;
			border-radius: 50rpx;
			background-color: #EfEfEf;
			padding-left: 20rpx;
			pointer-events:auto;
		}

		.city {
			display: flex;
			align-items: center;
			width: 130rpx;
			padding: 0 20rpx 0 0;
			// background-color: aqua;
			justify-content: space-between;

			.city_name {
				color: #000000;
				font-weight: 500;
				font-size: 26rpx;
				width: 120rpx;
				text-align: center;
				overflow: hidden; //超出的文本隐藏
				text-overflow: ellipsis; //溢出用省略号显示
				white-space: nowrap; //溢出不换行
			}

			.down {
				width: 18rpx;
				height: 12rpx;
			}
		}

		.line {
			width: 4rpx;
			height: 40rpx;
			background-color: #e9e9e9;
		}

		.keyword {
			font-size: 24rpx;
			flex: 1;
			height: 44rpx;
			font-weight: 500;
			color: #999999;
			margin-left: 20rpx;
		}

		.search_btn {
			padding: 8rpx 25rpx;
			margin-right: 10rpx;
			color: #fff;
			font-size: 24rpx;
			border-radius: 40rpx;
			background-color: #006cd9;
		}
	}
	.active{
		.menuList-title{
			.menuList-title-text{
				
				font-family: YouSheBiaoTiHei !important;
				color:#323232 !important;
				font-size: 30rpx !important;
			}
		}
	}
	.active1{
		.menuList-title{
			position: relative;
			.menuList-title-text{
				font-weight: 600 !important;
				color: #1D1D1D !important;
			}
			.menuList-title-line{
				width: 48rpx;
				height: 6rpx;
				background: #296DDD;
				position: absolute;
				bottom: 12rpx;
				left: 50%;
				z-index: -1;
				transform: translateX(-50%);
			}
		}
	}
	.menuList {
		white-space: nowrap;
		position: sticky;
		width: 100%;
		z-index: 95;
		transition: 0.1s;
		height: 140rpx;
		box-sizing: border-box;
		padding-bottom: 10rpx;
		.menuList-item {
			display: inline-block;
			width: 124rpx;
			height: 130rpx;
			.itemBox{
			}
			.menuList-img {
				width: 78rpx;
				height: 78rpx;
			}

			.menuList-title {
				height: 52rpx;
				margin-top: 5rpx;
				.menuList-title-text{
					font-size: 24rpx;
					font-weight: normal;
					line-height: 52rpx;
					color: #666;
				}
			}

		}
	}

	.content {
		.tejiatuan {
			margin-top: 10rpx;
			width: 100%;
			padding: 0 10rpx;

			.tejiatuan-title {
				padding: 0 24rpx;
				height: 24rpx;

				.title {
					font-family: YouSheBiaoTiHei;
					font-size: 36rpx;
					font-weight: normal;
					line-height: normal;
					text-align: center;
					color: #2F2F2F;
				}

				.heat {
					margin-left: 10rpx;
					height: 26rpx;
					border-radius: 10rpx;
					padding: 0 10rpx;
					background: linear-gradient(271deg, #FF3636 2%, #F6ADAD 113%);
					font-size: 18rpx;
					font-weight: normal;
					line-height: 24rpx;
					text-align: center;
					color: #F4EDED;
				}
			}

			.tejiatuan-goodsBox {
				width: 100%;

				.goodsBox-item {
					width: 50%;
					margin-top: 20rpx;
					padding: 0 20rpx;

					.item-img {
						width: 123rpx;
						height: 101rpx;
						min-width: 123rpx;
						margin-right: 14rpx;
						border-radius: 10rpx;
					}

					.item-right {
						height: 101rpx;

						.item-right-title {
							font-size: 24rpx;
							font-weight: 500;
							color: #000000;
						}

						.item-right-price {
							font-size: 24rpx;
							font-weight: 500;
							color: #F6481E;

							.price-line {
								text-decoration: line-through;
								font-size: 18rpx;
								font-weight: 500;
								color: #BFBFBF;
							}
						}
					}
				}
			}
		}
	}
</style>